<template>
  <div class="content-container">
    <div class="operator">
      <el-button
        size="small"
        type="primary"
        @click="openAddDlg()"
      >
        新增
      </el-button>
      <!--<el-button-->
      <!--size="small"-->
      <!--type="primary"-->
      <!--@click="goLogin()"-->
      <!--&gt;-->
      <!--注销-->
      <!--</el-button>-->
    </div>
    <el-table
      :data="jobsData"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="taskName"
        label="名称"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="factoryName"
        label="工厂"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="siteUrl"
        label="地址"
        min-width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="cron"
        min-width="120"
        label="cron表达式"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="状态"
        width="70"
      >
        <template slot-scope="rowScope">
          <job-status
            :status="rowScope.row.booleanStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="strAsLastSuccessMillis"
        label="上次成功"
        min-width="170"
      />
      <el-table-column
        prop="strAsLastFailMillis"
        label="上次失败"
        min-width="170"
      />
      <el-table-column
        prop="strAsLastDurationTimeMillis"
        label="持续时间"
      />
      <el-table-column
        label="操作"
        min-width="220"
      >
        <template slot-scope="rowScope">
          <el-button
            type="primary"
            size="mini"
            @click="onSync(rowScope.row.taskId)"
          >
            手动同步
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="openEditDlg(rowScope.row.taskId)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="mini"
            @click=" onDelete(rowScope.row.taskId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="任务"
      :visible.sync="dlgOpen"
    >
      <el-form
        ref="inputForm"
        :model="inputObj"
        :rules="computedRules"
        label-width="130px"
      >
        <el-form-item
          label="名称"
          prop="taskName"
        >
          <el-input
            v-model="inputObj.taskName"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="工厂"
          prop="factoryName"
        >
          <el-input
            v-model="inputObj.factoryName"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="cron表达式"
          prop="cron"
        >
          <el-input
            v-model="inputObj.cron"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="数据库链接"
          prop="dataSourceSetting.url"
        >
          <el-input
            v-model="inputObj.dataSourceSetting.url"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="数据库账号"
          prop="dataSourceSetting.username"
        >
          <el-input
            v-model="inputObj.dataSourceSetting.username"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="数据库密码"
          prop="dataSourceSetting.password"
        >
          <el-input
            v-model="inputObj.dataSourceSetting.password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="应用类型"
          prop="appType"
        >
          <el-select v-model.number="inputObj.appType">
            <el-option
              label="IOT应用"
              :value="1"
            />
            <el-option
              label="普通应用"
              :value="2"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          prop="appKey"
          label="AppKey"
        >
          <el-input
            v-model="inputObj.appKey"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          v-if="inputObj.appType===1"
          prop="appSecret"
          label="AppSecret"
        >
          <el-input
            v-model="inputObj.appSecret"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="应用上下文地址"
          prop="siteUrl"
        >
          <el-input
            v-model="inputObj.siteUrl"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="账户"
          prop="accountInfo"
        >
          <el-select
            v-model="inputObj.accountInfo.accountId"
            placeholder="请选择"
          >
            <el-option
              v-for="account in accounts"
              :key="account.accountId"
              :label="account.accountName"
              :value="account.accountId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="状态"
          prop="status"
        >
          <el-switch
            v-model.number="inputObj.status"
            style="display: block"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="是"
            no-data-text="请选择"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dlgOpen = false">
          取 消
        </el-button>
        <el-button
          type="primary"
          @click="submitInput"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import {
  getTaskPageData,
  getTaskInfoData,
  putTaskInfoData,
  deleteTaskData,
  postTaskInfoData,
  postSyncData
} from '@/api/task-api'
import {
  getAccountsData
} from '@/api/account-api'
import JobStatus from '@/views/task/components/JobStatus.vue'
import { IJob } from '@/api/types'

  @Component({
    name: 'Job',
    components: {
      JobStatus
    }
  })
export default class extends Vue {
    private jobsData: IJob[] = []
    private dlgOpen: Boolean = false
    private inputObj: any = {
      dataSourceSetting: {},
      accountInfo: {
        accountId: ''
      }
    }
    private accounts: any = []

    mounted() {
      this.$nextTick(() => this.initPageData())
    }

    get computedRules() {
      return {
        taskName: [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        factoryName: [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        cron: [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        'dataSourceSetting.url': [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        'dataSourceSetting.username': [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        'dataSourceSetting.password': [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        'appType': [
          { required: true, message: '请选择', trigger: 'blur' }
        ],
        'appKey': [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        'appSecret': [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        'siteUrl': [
          { required: true, message: '请填写', trigger: 'blur' }
        ]
      }
    }

    private async initPageData() {
      this.jobsData = await getTaskPageData({})
    }

    private async submitInput() {
      let { inputObj: { id }, inputObj } = this
      // validate
      const inputForm = this.$refs['inputForm']
      if (inputForm) {
        (inputForm as any).validate(async(valid: boolean) => {
          if (valid) {
            let response
            if (id) {
              // 更新任务
              response = await putTaskInfoData(id, inputObj)
            } else {
              // 新增任务
              response = await postTaskInfoData(inputObj)
            }
            if (response) {
              this.dlgOpen = false
              this.kdcNotify(' 成功 ')
              await this.initPageData()
            }
          }
        })
      }
    }

    private kdcNotify(message: String) {
      this.$notify({
        message: message,
        type: 'success',
        duration: 2000
      })
    }

    private async onDelete(id: number) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTaskData(id).then(response => {
          if (response) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initPageData()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

    private async onSync(id: number) {
      const response = await postSyncData(id)
      if (response) {
        this.kdcNotify('同步已开始')
      }
    }

    // 打开新增 对话框
    private async openAddDlg() {
      this.resetInputObj()
      this.accounts = await getAccountsData()
      this.dlgOpen = true
    }

    private resetInputObj() {
      this.inputObj = {
        dataSourceSetting: {},
        accountInfo: {
          accountId: ''
        }
      }
    }

    /**
     * 打开 编辑 框
     */
    private async openEditDlg(id: number) {
      console.info('open 编辑框', id)
      this.dlgOpen = true
      this.accounts = await getAccountsData()
      this.inputObj = await getTaskInfoData(id)
    }
}
</script>

<style scoped lang="scss">
  .content-container {
    margin: 10px;

    .operator {
      margin: 0 0 10px 10px;
      text-align: right;
    }

    .el-input--medium {
      width: 350px;
      margin-right: 20px;
    }

    ::v-deep .el-dialog {
      width: 540px;
    }

    ::v-deep .el-switch {
      padding-top: 7px;
    }

    ::v-deep .el-dialog__body {
      max-height: 60vh;
      overflow: auto;
    }
  }
</style>
